package com.daowei.dwdemo.dao;

import com.daowei.dwdemo.utils.SQLModel;
import com.daowei.dwdemo.utils.SQLUtils;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.templates.SqlTemplate;

import java.util.Collections;


@Singleton
public class DatabaseService {

  private final MySQLPool client;

  @Inject
  public DatabaseService(Vertx vertx) {
    System.out.println("database: " + vertx);
    MySQLConnectOptions connectOptions = new MySQLConnectOptions()
        .setPort(3306)
        .setHost("localhost")
        .setDatabase("sweet")
        .setUser("root")
        .setPassword("123456");
    PoolOptions poolOptions = new PoolOptions()
        .setMaxSize(5);
    client = MySQLPool.pool(vertx, connectOptions, poolOptions);
  }

  public Future<JsonArray> queryBook() {
    SQLModel sqlModel = SQLUtils.sql("SELECT * FROM book WHERE id=#{id}",
        Collections.singletonMap("id", 1));
    return SqlTemplate
        .forQuery(client, sqlModel.sql)
        .execute(sqlModel.parameters)
        .map(rows -> {
          JsonArray array = new JsonArray();
          for (Row row : rows) {
            array.add(row.toJson());
          }
          return array;
        });
  }
}
